package com.laobiao.paChong.wanyijunshi.sina.execut;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.laobiao.paChong.wanyijunshi.exception.PaChongException;
import com.laobiao.paChong.wanyijunshi.sina.model.SinaContentModel;
import com.laobiao.paChong.wanyijunshi.util.HttpClientUtil;

public class ExecuteSinaList implements Runnable{
	private ExecutorService fixedThreadPool;
	private int form;
	private int end;
	private String baseDir;
	private String listurl;
	/**
	 * 
	 * @param form 开始页数
	 * @param end 结束页数
	 * @param tc 同时运行线程数
	 * @param baseDir 基础存储路径
	 * @param listurl 翻页url 页码用@D@表示
	 */
	public ExecuteSinaList(int form,int end,int tc,String baseDir,String listurl){
		if(form<=0 || form>end || tc<=0){
			throw new PaChongException("新浪新闻分页条件或活跃线程数配置错误！");
		}
		if(StringUtils.isEmpty(baseDir)){
			throw new PaChongException("新浪新闻文件存储目录未配置");
		}
		fixedThreadPool = Executors.newFixedThreadPool(tc);
		this.form=form;
		this.end=end;
		this.baseDir=baseDir;		
		this.listurl=listurl;
		
	}
	
	@Override
	public void run() {
		
		Map<String, String> headers=new HashMap<>();
		headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36");
		headers.put("Accept-Language", "zh-CN,zh;q=0.8");
		headers.put("Accept-Encoding", "gzip, deflate");
		String[] listUrl=listurl.split("@D@");
		for(int i = form;i<end;i++){
			String s=HttpClientUtil.sendGetRequest(listUrl[0]+i+listUrl[1], null,headers,"GBK");
			
			if(!s.equals("通信失败")){
				Document doc = Jsoup.parse(s);
				Elements newsUl = doc.select(".linkNews > li");
				if(newsUl!=null && !newsUl.isEmpty()){
					fixedThreadPool.execute(new ExecuteSinaZw(newsUl,baseDir));
				}
				
			}
			
		}
		
		/**
		 * 执行完成后关闭
		 */
		boolean wait=true;
		while(wait){
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			int threadCount = ((ThreadPoolExecutor)fixedThreadPool).getActiveCount();
			//System.out.println(threadCount);
			if(threadCount<=0){
				fixedThreadPool.shutdown();
				wait=false;
			}
		}
		
	}

}
